import productData from "./productData";
import {isEmpty, isNotEmpty} from "../../../js/commonUtils";

export const initPageInfo = () => {
  //查询参数
  productData.tParam.searchParam.categories.splice(0);
  productData.tParam.searchParam.pCode = "";
  productData.tParam.searchParam.shopId = "";
  productData.tParam.searchParam.state = 1;
  productData.tParam.searchParam.startTime = null;
  productData.tParam.searchParam.endTime = null;
  productData.tParam.searchParam.from = null;
  productData.tParam.searchParam.tag = null;
  productData.tParam.searchParam.hasBanned = 0;
  productData.tParam.searchParam.isAuditable = true;
  productData.tParam.searchParam.author = "";

  //分页
  productData.tPage.listPage.pageNum = 1;
  productData.tPage.listPage.pageSize = 40;
  productData.tPage.listPage.total = 0;

  //数据
  productData.tData.list.splice(0);
}

export const queryProductList = (self) => {
  let params = productData.tParam.searchParam;
  params.pageNum = productData.tPage.listPage.pageNum;
  params.pageSize = productData.tPage.listPage.pageSize;
  self.$Spin.show();
  self.$apiImpProduct.queryProductList(params).then(response => {
    self.$Spin.hide();
    productData.tData.list.splice(0);
    if(response.success) {
      let page = response.result;
      productData.tData.list.push(...page.list);
      productData.tPage.listPage.total = page.total;
    }else{
      self.$Message.error(response.errorMessage);
    }
  });
}

export const deleteProduct = (self, id) => {
  let params = {id: id};
  self.$Spin.show();
  self.$apiImpProduct.deleteProduct(params).then(response => {
    self.$Spin.hide();
    if(response.success) {
      self.$Message.success("删除成功！");
      queryProductList(self);
    }else{
      self.$Message.error(response.errorMessage);
    }
  })
}

export const modifyProduct = (self, isAudit) => {
  let params = {};
  params.product = productData.tParam.modifyParam;
  params.isAudit = isAudit;

  let errMsgDuration = 5;
  if(isEmpty(params.product.titleEn)) {
    self.$Message.error({content: "产品英文名称不能为空！", duration: errMsgDuration});
    return;
  }
  if(params.product.titleEn.length > 150) {
    self.$Message.error({content: "产品英文名称长度不能超过150个字符！", duration: errMsgDuration});
    return;
  }
  if(isEmpty(params.product.weight)) {
    self.$Message.error({content: "计费重量不能为空！", duration: errMsgDuration});
    return;
  }
  if(params.product.categories==null || params.product.categories.length==0) {
    self.$Message.error({content: "采集分类不能为空！", duration: errMsgDuration});
    return;
  }
  // if(params.product.categories.length<=1) {
  //   self.$Message.error({content: "至少选择2级分类！", duration: errMsgDuration});
  //   return;
  // }
  if(isEmpty(params.product.priceUnit)) {
    self.$Message.error({content: "价格单位不能为空！", duration: errMsgDuration});
    return;
  }
  let price = params.product.prices.find(element => isEmpty(element.usdPrice));
  if(price != null) {
    self.$Message.error({content: "保底价格不能为空！", duration: errMsgDuration});
    return;
  }
  //如果有尺码表
  if(params.product.sizeTable.length > 0) {
    for(let i=0; i<params.product.sizeTable.length; i++) {
      let row = params.product.sizeTable[i];
      let index = row.findIndex(cell => isEmpty(cell));
      if(index > -1) {
        let msg = "产品尺码表不能有空值";
        self.$Message.error({content: msg, duration: errMsgDuration});
        return;
      }
    }
  }

  let attr = params.product.attrs.find(element => isEmpty(element.nameEn) || isEmpty(element.valueEn));
  if(attr != null) {
    let msg = "产品属性["+attr.name+"]"+(isEmpty(attr.nameEn)?"的英文名称":"英文值")+"不能为空";
    self.$Message.error({content: msg, duration: errMsgDuration});
    return;
  }

  attr = params.product.attrs.find(element => element.nameEn.length>100 || element.valueEn.length>200);
  if(attr != null) {
    let msg = "产品属性["+attr.name+"]"+(attr.nameEn.length>100?"的名称英文长度不能超过100个字符":"的值英文长度不能超过200个字符");
    self.$Message.error({content: msg, duration: errMsgDuration});
    return;
  }

  for(let i=0; i<params.product.colors.length; i++) {
    let size = params.product.colors[i].sizes.find(element => element.nameEn.length>40);
    if(size != null) {
      let msg = "产品色卡["+params.product.colors[i].name+"]中的尺码["+size.name+"]英文长度不能超过40个字符";
      self.$Message.error({content: msg, duration: errMsgDuration});
      return;
    }
  }

  self.$refs.impProductForm.validate(valid => {
    if(valid) {
      self.$Spin.show();
      self.$apiImpProduct.updateProduct(params).then(response => {
        self.$Spin.hide();
        if(response.success) {
          self.$Message.success("修改成功！");
          productData.tStatus.modifyModal.isShow = false;
          queryProductList(self);//刷新页面
        }else{
          self.$Message.error({content: response.errorMessage, duration: 3});
        }
      })
    }else{
      console.log("validate failed!")
    }
  });
}

export const importToFormalLib = (self, ids) => {
  self.$Modal.confirm({
    title: "确认",
    content: "确定要将"+(ids.length==1?"此":"这些")+"产品导入正式库吗？",
    onOk() {
      let params = {ids: ids};
      self.$Spin.show();
      self.$apiImpProduct.importProduct(params).then(response => {
        self.$Spin.hide();
        if(response.success) {
          self.$Message.success("导入完成！");
          queryProductList(self);
        }else{
          self.$Message.error(response.errorMessage);
        }
      })
    }
  })
}

export const saveProductTags = (self) => {
  let params = productData.tParam.tagsParam;
  self.$Spin.show();
  self.$apiImpProduct.saveProductTags(params).then(response => {
    self.$Spin.hide();
    if(response.success) {
      self.$Message.success("保存成功！");
      queryProductList(self);
    }else{
      self.$Message.error(response.errorMessage);
    }
  });
}

export const queryMongoCategories = (self, categoryTree) => {
  self.$apiImpProduct.queryAllCategories().then(response => {
    categoryTree.splice(0);
    if(response.success) {
      let result = response.result;
      let treeData = makeTreeData(result);
      categoryTree.push(...treeData);
    }else{
      console.error(response.errorMessage);
      self.$Message.error("采集分类查询失败");
    }
  }).catch(() => {
    self.$Message.error("采集分类查询失败");
  });
}

const makeTreeData = (categoryList) => {
  let catsLevel1 = [];
  let catsLevel2 = [];
  let catsLevel3 = [];
  for(let cat of categoryList) {
    let item = {value: cat.id, label: cat.name, parentId: cat.parentId};
    switch(cat.level) {
      case 1:
        item.children = [];
        catsLevel1.push(item);
        break;
      case 2:
        item.children = [];
        catsLevel2.push(item);
        break;
      case 3:
        catsLevel3.push(item);
        break;
    }
  }
  //构建分类树形json
  //2，3级分类
  for(let cat2 of catsLevel2) {
    for(let cat3 of catsLevel3) {
      if(cat3.parentId == cat2.value) {
        cat2.children.push(cat3);
      }
    }
  }
  //1,2级分类
  for(let cat1 of catsLevel1) {
    for(let cat2 of catsLevel2) {
      if(cat2.parentId == cat1.value) {
        cat1.children.push(cat2);
      }
    }
  }
  return catsLevel1;
}

export const banProducts = (self) => {
  let params = productData.tParam.banParam;
  self.$Spin.show();
  self.$apiImpProduct.bannedProducts(params).then(response => {
    self.$Spin.hide();
    if(response.success) {
      self.$Message.success("操作成功！");
      productData.tStatus.banModal.isShow = false;
      queryProductList(self);
    }else{
      self.$Message.error(response.errorMessage);
    }
  });
}

export const cancelBanProducts = (self) => {
  let params = productData.tParam.banParam;
  self.$Spin.show();
  self.$apiImpProduct.cancelBannedProducts(params).then(response => {
    self.$Spin.hide();
    if(response.success) {
      self.$Message.success("操作成功！");
      queryProductList(self);
    }else{
      self.$Message.error(response.errorMessage);
    }
  });
}

export const removeNonExistImages = (self, product) => {
  let params = {pCode: product.pCode};
  self.$Spin.show();
  self.$apiImpProduct.queryImagesByPCode(params).then(response => {
    self.$Spin.hide();
    if(response.success) {
      let uploadedImgKeys = response.result;
      if(uploadedImgKeys==null || uploadedImgKeys.length == 0) {
        product.mainImgs.splice(0);
        product.productImgs.splice(0);
      }else{
        let mainImgs = [];
        let detailImgs = [];
        if(product.mainImgs!=null && product.mainImgs.length>0) {
          for(let i=0; i<product.mainImgs.length; i++) {
            let mainImg = product.mainImgs[i];
            if(uploadedImgKeys.findIndex(img => img.replace("products/", "")==mainImg.colorImg) > -1) {
              mainImgs.push(mainImg);
            }
          }
          product.mainImgs.splice(0);
          product.mainImgs.push(...mainImgs);
        }
        if(product.productImgs!=null && product.productImgs.length>0) {
          for(let i=0; i<product.productImgs.length; i++) {
            let detailImg = product.productImgs[i];
            if(uploadedImgKeys.findIndex(img => img.replace("products/", "")==detailImg.colorImg) > -1) {
              detailImgs.push(detailImg);
            }
          }
          product.productImgs.splice(0);
          product.productImgs.push(...detailImgs);
        }
      }
    }else{
      console.log(response.errorMessage);
      self.$Message.error("查询已上传图片失败！")
    }
  }).catch(() => {
    self.$Spin.hide();
    self.$Message.error("查询已上传图片失败！")
  });
}

//重新采集图片
export const recollectImages = (self, productId) => {
  let params = {id: productId};
  self.$Spin.show();
  self.$apiImpProduct.collectImages(params).then(response => {
    self.$Spin.hide();
    if(response.success) {
      self.$Message.success("重新采集完成");
      self.imgParam = new Date().getTime();
    }else{
      console.error(response);
      self.$Message.error({content: "重新采集产品图片失败"+response.errorMessage, duration: 3});
    }
  }).catch(err => {
    self.$Spin.hide();
    console.error(err);
    self.$Message.error({content: "重新采集产品图片失败", duration: 3});
  })
}


export const modifyBatchUpdateProduct = (self, isAudit) => {
  let params = {};
  params.ids = self.selectedIds;
  params.isAudit = isAudit;
  params.batchCategoryId = self.batchCategoryId;
  params.batchPriceUnit = self.batchPriceUnit;
  self.$Spin.show();
  self.$apiImpProduct.batchUpdateProduct(params).then(response => {
    self.$Spin.hide();
    if(response.success) {
      self.$Message.success("批量修改成功！");
      productData.tStatus.modifyModal.isShow = false;
      queryProductList(self);//刷新页面
    }else{
      self.$Message.error({content: response.errorMessage, duration: 3});
    }
  });
}
